package src.java.difficulty;

public class Solution25 {
    public  boolean hasEnoughNodes(ListNode head, int k) {
        int count = 0;
        ListNode current = head;
        while (current != null) {
            count++;
            current = current.next;
        }
        return count >= k;
    }


    public  ListNode reverseKGroup(ListNode head, int k) {
        if (!hasEnoughNodes(head, k)) return head;
        ListNode moved = move(head, k);
        ListNode tail = reverseKGroup(moved, k);
        ListNode newHead = reverse(head, k);
        head.next = tail;
        return newHead;
    }

    private  ListNode reverse(ListNode node, int k) {
        ListNode prev = null;
        ListNode curr = node;
        int count = 0;
        while (count < k) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
            count++;
        }
        return prev;
    }

    public  ListNode move(ListNode node, int k) {
        int count = 0;
        while (count < k) {
            node = node.next;
            count++;
        }
        return node;
    }


}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
